<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<meta name="renderer" content="webkit|ie-comp|ie-stand">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
<!--[if lt IE 9]>
<script type="text/javascript" src="/js/html5.js"></script>
<script type="text/javascript" src="/js/respond.min.js"></script>
<script type="text/javascript" src="/js/PIE_IE678.js"></script>
<![endif]-->
<link href="/assets/css/bootstrap.min.css" rel="stylesheet" />
<link rel="stylesheet" href="/css/style.css"/>
<link href="/assets/css/codemirror.css" rel="stylesheet">
<link rel="stylesheet" href="/assets/css/ace.min.css" />
      <link rel="stylesheet" href="/Widget/zTree/css/zTreeStyle/zTreeStyle.css" type="text/css">
<link rel="stylesheet" href="/assets/css/font-awesome.min.css" />
<!--[if IE 7]>
		  <link rel="stylesheet" href="/assets/css/font-awesome-ie7.min.css" />
		<![endif]-->
<link href="/Widget/icheck/icheck.css" rel="stylesheet" type="text/css" />
<link href="/Widget/webuploader/0.1.5/webuploader.css" rel="stylesheet" type="text/css" />

<script src="/js/jquery-1.9.1.min.js"></script>
<script src="/assets/js/bootstrap.min.js"></script>
<script src="/assets/js/typeahead-bs2.min.js"></script>
<script src="/assets/layer/layer.js" type="text/javascript" ></script>
<script src="/assets/laydate/laydate.js" type="text/javascript"></script>
<script type="text/javascript" src="/Widget/My97DatePicker/WdatePicker.js"></script>
<script type="text/javascript" src="/Widget/icheck/jquery.icheck.min.js"></script>
<script type="text/javascript" src="/Widget/zTree/js/jquery.ztree.all-3.5.min.js"></script>
<script type="text/javascript" src="/Widget/Validform/5.3.2/Validform.min.js"></script>
<script type="text/javascript" src="/Widget/webuploader/0.1.5/webuploader.min.js"></script>
<script type="text/javascript" src="/Widget/ueditor/1.4.3/ueditor.config.js"></script>
<script type="text/javascript" src="/Widget/ueditor/1.4.3/ueditor.all.min.js"> </script>
<script type="text/javascript" src="/Widget/ueditor/1.4.3/lang/zh-cn/zh-cn.js"></script>
<script src="/js/lrtk.js" type="text/javascript" ></script>
<script type="text/javascript" src="/js/H-ui.js"></script>
<script type="text/javascript" src="/js/H-ui.admin.js"></script>
<title>订单修改</title>
</head>
<body>
<div class="clearfix" id="add_picture">
  </div>
  </div>  
  </div>
   <div class="page_right_style" >
   <div class="type_title">订单修改</div>
   
   
	<form action="" method="post" class="form form-horizontal" id="form-article-add" onsubmit="return checkAll()">

		<div class="clearfix cl">
         <label class="form-label col-2"><span class="c-red">*</span>客户：</label>
				<!--<div class="formControls col-10" width="300px"><select class="select" id="customer_select">
					<option value="0">请选择</option>
					<option th:each="c:${customers}"
							th:value="${c.id}"
							th:text="${c.name}">
					</option>
				</select>
					<span id="customerInfo" style="color: red;"></span>
				</div>-->
			<label class="form-label col-2"><span th:text="${salesOrder.customer.name}"></span></label>
		</div>
		<div class="border clearfix">
		   <span class="l_f">
			<a href="javascript:void(0)" onclick="addProduct()" title="添加商品" class="btn btn-warning Order_form"><i class="icon-plus"></i>添加商品</a>
               <a href="javascript:void(0)" onclick="removeAll()" title="清空商品" class="btn btn-danger Order_form"><i class="icon-trash"></i>清空商品</a>
		   </span>
		</div>
		<div class="clearfix cl">
			<table class="table table-striped table-bordered table-hover" id="product_table">
				<thead>
					<tr>
						<th>商品编号</th>
						<th>商品名称</th>
						<th>价格</th>
						<th>数量</th>
						<th>小计</th>
						<th>操作</th>
					</tr>
				</thead>
				<tbody>
					<tr th:each="detail:${details}" class='data_tr'>
						<td th:text="${detail['pid']}"></td>
						<td th:text="${detail['pname']}"></td>
						<td th:text="${detail['psalesprice']}+${detail['punit']}"></td>
						<td><input th:value="${detail['pamount']}" onchange="doOnAmoutChange(this)"></td>
						<td th:text="${detail['psalesprice']}*${detail['pamount']}+元"></td>
						<td><a title='删除' href='javascript:;' onclick='removeProduct(this)' class='btn btn-xs btn-danger' ><i class='icon-trash  bigger-120'></i>删除</a></td>
					</tr>
				</tbody>
			</table>
			<p>总计：<span id="total">0</span>元</p>
		</div>

        
        
		<div class="clearfix cl">
			<div class="Button_operation">
				<button onclick="submitSalesOrder();" class="btn btn-primary radius" type="button"><i class="icon-save "></i>修改</button>
				<button onclick="layer_close();" class="btn btn-default radius" type="button"><i class="icon-undo "></i>返回</button>
			</div>
		</div>
	</form>
    </div>
</div>
</div>

<!--添加商品弹窗-->
<div id="addProduct" style="display: none">
	<div>
		<label class="form-label col-2"><span class="c-red">*</span>商品种类：</label>
		<select class="select" id="protype_select" name="protypes" onchange="getProductByType()">
			<option value="0" selected="selected">请选择</option>
			<option th:each="p:${protypes}"
					th:value="${p.protype_id}"
					th:title="${p.protype_name}"
					th:text="${p.protype_name}">
			</option>
		</select>
		<span id="protypeInfo" style="color: red;"></span>
	</div>
		<div>
			<label class="form-label col-2"><span class="c-red">*</span>商品：</label>
			<select class="select" id="pro_select">
                <option value="0" selected="selected">请选择</option>
			</select>
			<span id="proInfo" style="color: red;"></span>
		</div>
		<div >
			<label class="form-label col-2"><span class="c-red">*</span>数量：</label>
			<input type="text" class="input-text" value="" placeholder="" id="amount" name="amount">
			<span id="amountInfo" style="color: red;"></span>
		</div>
</div>
<script th:inline="javascript">
$(function(){
	init();
})

//初始化总计和小计
function init(){
	$("#product_table tbody tr").each(function(i,obj){
		var subtotal = Number.parseFloat($(obj).find("input").val())*Number.parseFloat($(obj).find("td").eq(2).text());
		$(obj).find("td").eq(4).text(subtotal+"元");
	})
	updateTotal();
}

/*判断是否已经选择客户*/
function isCustomerSelected(){
	var cid = $("#customer_select option:selected").val();
	if(cid==0){
		layer.msg('请先选择客户！', {
			icon: 7,
			time: 1500 //2秒关闭（如果不配置，默认是3秒）
		})
		return false;
	}else {
		return true;
	}
}

/*判断表中是否有数据*/
function isHasData(){
	var length = $("#product_table tbody tr[class='data_tr']").size();
	if(length==0){
		return false;
	}else{
		return true;
	}
}


/*		layer.msg('同上', {
			icon: 1,
			time: 2000 //2秒关闭（如果不配置，默认是3秒）
		}, function(){
			//do something
		});*/

/*添加商品提交时，判断是否选择了商品*/
function checkProductSelected() {
    var pid = $("#pro_select option:selected").val();
    if(pid == 0){
		$("#proInfo").text('请选择商品');
		return false;
    }else{
		$("#proInfo").text('');
        return true;
    }
}

/*添加商品时，检查输入的数量是否合法*/
function checkAmount(obj) {
    var amount = $(obj).val();
    if(amount==null || amount.trim()==''){
    	$("#amountInfo").text('请输入商品数量，最少为一件');
        return false;
    }else{
        var reg = /^[1-9]\d*$/;
        if(reg.test(amount)){
			$("#amountInfo").text('');
            return true;
        }else{
			$("#amountInfo").text('请输入正整数！');
            return false;
        }
    }
}

function submitSalesOrder() {
	//提交之前先进行校验，判断是否选择了商品和客户
	if (!isHasData()){
		layer.msg('请先选择商品！', {
			icon: 0,
			time: 1500 //2秒关闭（如果不配置，默认是3秒）
		});
	}else{
		//提交操作
		var oid = [[${salesOrder.id}]];
		//客户id
		//var cid = $("#customer_select option:selected").val();
		//定义了商品id和数量的数组
		var pids = [];
		var amounts = [];
		$(".data_tr").each(function(i,obj){
			//alert("id"+i+":"+$(obj).find("td").eq('0').text());
			pids.push($(obj).find("td").eq('0').text());
		})
		$(".data_tr").each(function(i,obj){
			//alert("amount"+i+":"+$(obj).find('input').val());
			amounts.push($(obj).find('input').val());
		})
		//封装成需要发送给后端的数据
		var data = {
			oid:oid,
			//cid:cid,
			pids:pids,
			amounts:amounts
		};
		//console.log(data);
		$.get("/salesOrder/updateById",data,function(result){
			if(result==1){
				layer.msg('修改成功！', {
					icon: 1,
					time: 1500 //2秒关闭（如果不配置，默认是3秒）
				},function () {
  					window.history.go(-1);
				});
			}else{
				layer.msg('修改失败，请联系系统管理员！', {
					icon: 0,
					time: 1500 //2秒关闭（如果不配置，默认是3秒）
				});
			}
		})
	}
}

/*通过分类获取商品*/
function getProductByType() {
	var typeID = $("#protype_select option:selected").val();
	//alert(typeID);
	$.getJSON("/salesOrder/getProductByType","typeid="+typeID,function(data){
		//console.log(data);
		$("#pro_select").html('<option value="0" selected="selected">请选择</option>');
		$.each(data,function(i,obj){
			/*根据商品种类生成商品下拉列表选项*/
			$("#pro_select").append('<option title="'+obj.product_salesprice+obj.product_unit+'" value="'+obj.product_id+'">'+obj.product_name+'</option>')
		})
	})
}

/*添加商品*/
function addProduct() {
	//使商品种类选中默认的"请选择"
	$("#protype_select option[value='0']").prop("selected","selected");
	$("#pro_select option[value='0']").prop("selected","selected");
	$("#amount").val('');
	/*获取商品列表*/
	layer.open({
		type: 1,
		title: '添加商品',
		area: ['500px', '300px'],
		shadeClose: true,
		content: $('#addProduct'),
		btn: ['确认','取消'],
		yes: function (index, layero) {
		    var checkflag =checkProductSelected() & checkAmount($("#amount"));
            if(checkflag==1){
                var proID = $("#pro_select option:selected").val();
                var amount = $("#amount").val();
                var price = $("#pro_select option:selected").prop("title");//带单位的价格
                var isProductExist = false; //判断是否已经有了该商品

                $.each($("#product_table tbody tr"),function(){
                    var id = $(this).find("td").eq('0').text();
                    if(id==proID){
                        isProductExist=true;
                        /*如果id在已有的列表中找得到，当前数量加上新增的数量*/
                        var oldAmount =  $(this).find("input").val();
                        var newAmount = Number.parseFloat(oldAmount)+Number.parseFloat(amount);
                        //更新数量
                        $(this).find("input").val(newAmount);
                        //更新小计
                        $(this).find("td").eq('4').text(accMul(Number.parseFloat(newAmount),Number.parseFloat(price))+"元");
                        //更新总计
                        updateTotal();
                        /*列表中已经有了该商品，标志量置为false*/
                    }
                });
                if(isProductExist){
                    layer.close(index);
                    return;
                }else{
                    var proName = $("#pro_select option:selected").text();
                    var subtotal = accMul(amount,Number.parseFloat(price));
                    //如果不含商品数据，把默认的信息提示tr删掉，然后再添加
                    if(!isHasData()){
                    	$("#product_table tbody").html('');
					}
                    $("#product_table tbody").append("<tr class='data_tr'><td>"+proID+"</td><td>"+proName+"</td><td>"+price+"</td><td><input value='"+amount+"' onchange='doOnAmoutChange(this)' onfocus='saveOldAmout(this)'></td><td>"+subtotal+"元</td><td><a title='删除' href='javascript:;' onclick='removeProduct(this)' class='btn btn-xs btn-danger' ><i class='icon-trash  bigger-120'></i>删除</a></td></tr>");
                    updateTotal();
                    layer.close(index);
                }
            }
		}
	})
}
/*定义了一个全局变量，保存数量旧值*/
var currentAmount;

/*点击input，保存以前的value，以便于数据回滚*/
function saveOldAmout(obj){
	currentAmount = $(obj).val();
}

/*表格中价格发生改变时，先进行校验，通过后更新该行小计和总计*/
function doOnAmoutChange(obj){
    var newAmount =  $(obj).val();
	if(newAmount==null || newAmount.trim()==''){
		layer.msg('商品数量不能为空', {
			icon: 0,
			time: 1500 //2秒关闭（如果不配置，默认是3秒）
		});
		//数据回滚
		$(obj).val(currentAmount);
	}else{
		var reg = /^[1-9]\d*$/;
		if(!reg.test(newAmount)){
			layer.msg('请输入正整数！', {
				icon: 0,
				time: 1500 //2秒关闭（如果不配置，默认是3秒）
			});
			//数据回滚
			$(obj).val(currentAmount);
		}else{
			var price = $(obj).parents("tr").find("td").eq(2).text();
			//更新小计
			$(obj).parents("tr").find("td").eq(4).text(accMul(Number.parseFloat(price),Number.parseFloat(newAmount))+"元");
			//更新总计
			updateTotal();
		}
	}
}

/*移除所有商品记录*/
function removeAll() {
    $("#product_table tbody").html('');
    updateTotal();
	$("#product_table tbody").html('<tr><td colspan="100">暂无任何商品信息！</td></tr>');
}

/*移除一条商品记录*/
function removeProduct(obj){
	//$(obj).parent().parent().remove();第一种写法
	$(obj).parents("tr").remove();
	updateTotal();
	if(!isHasData()){
		$("#product_table tbody").html('<tr><td colspan="100">暂无任何商品信息！</td></tr>');
	}
}

/*更新总计*/
function updateTotal() {
	var total = 0;
	$.each($("#product_table tbody tr"),function(){
		var subtotal=$(this).find("td").eq(4).text();
		total = Number.parseFloat(subtotal)+total;
	})
	$("#total").html(total);
}

//解决js浮点数乘法不精确的bug
function accMul(arg1, arg2) {
	var m = 0, s1 = arg1.toString(), s2 = arg2.toString();
	try {
		m += s1.split(".")[1].length;
	}
	catch (e) {
	}
	try {
		m += s2.split(".")[1].length;
	}
	catch (e) {
	}
	return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
}

/*返回列表页面*/
function layer_close(){
	window.history.go(-1);
}
	
$(function() { 
	$("#add_picture").fix({
		float : 'left',
		skin : 'green',	
		durationTime :false,
		stylewidth:'220',
		spacingw:0,
		spacingh:260,
	});
});


$( document).ready(function(){
//初始化宽度、高度
  
   $(".widget-box").height($(window).height());
   $(".page_right_style").height($(window).height()); 
   $(".page_right_style").width($(window).width());
  //当文档窗口发生改变时 触发  
    $(window).resize(function(){

	 $(".widget-box").height($(window).height()); 
	 $(".page_right_style").height($(window).height()); 
	 $(".page_right_style").width($(window).width());
	});	
});
		
var code;
		
function showCode(str) {
	if (!code) code = $("#code");
	code.empty();
	code.append("<li>"+str+"</li>");
}
</script>
</body>
</html>